// src/components/ReadERC20.tsx
import React, {useEffect, useState } from 'react'
import {Text} from '@chakra-ui/react'
import {TodoABI as abi} from 'abi/TodoABI'
import {Signer, ethers} from 'ethers'
import { Contract } from "ethers"

interface Props {
    addressContract: string,
    currentAccount: string | undefined
}

declare let window: any
const addressContract = '0x5FbDB2315678afecb367f032d93F642f64180aa3'
export default function ReadTodo(props:Props){
  //const context = useweb<Provider>();
 
   const currentAccount = props.currentAccount
   const [totalSupply,setTotalSupply]=useState<string>()
   const [symbol,setSymbol]= useState<string>("")
   const [balance, SetBalance] =useState<number|undefined>(undefined)
 
  useEffect( () => {
    //doConnect()
    if(!window.ethereum) return

    const provider = new ethers.providers.Web3Provider(window.ethereum)
    
    const erc20 = new ethers.Contract(addressContract, abi, provider);
    // erc20.symbol().then((result:string)=>{
    //     setSymbol(result)
    // }).catch('error', console.error)

    // erc20.totalSupply().then((res:string)=>{
    //   setTotalSupply(ethers.utils.formatEther(res))
    // }).catch('error',console.error)


     queryTokenBalance(window)
    // const fromMe = erc20.filters.Transfer(currentAccount,null)
    // erc20.on(fromMe,(form,to,amount,event)=>{
    //   queryTokenBalance(window)
    // })

    // const toMe = erc20.filters.Transfer(null,currentAccount)
    // erc20.on(toMe,(form,to,amount,event)=>{
    //   queryTokenBalance(window)
    // })

    // return ()=>{
    //   erc20.removeAllListeners(toMe)
    //   erc20.removeAllListeners(fromMe)
    // }

  //   const toMe = erc20.filters.Transfer(null, currentAccount)
  //   erc20.on(toMe, (from, to, amount, event) => {
  //       console.log('Transfer|received',  {from, to, amount, event} )
  //       queryTokenBalance(window)
  //   })

  //   // remove listener when the component is unmounted
  //   return () => {
  //       erc20.removeAllListeners(toMe)
  //       erc20.removeAllListeners(fromMe)
  //   }  


    
  
  },[currentAccount])  

  
  async function queryTokenBalance(window:any){
    //const provider = new ethers.providers.Web3Provider(window.ethereum)
    //const erc20:Contract = new ethers.Contract(addressContract, abi, provider);


    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const singer = provider.getSigner();
    // 可写合约
    const contract = new ethers.Contract(addressContract,abi,singer)
    console.log('创建todo')
    // try{
    //   const data =  await contract.create('11111111111');
    //   console.log(data)
    // }catch(err){
    //   console.log(`err: ${err}`)
    // }
    
   
    console.log("读取text1")

    await contract.get(0).then((result:string)=>{
        console.log(result)
         //SetBalance(Number(ethers.utils.formatEther(result)))
      }).catch((e:Error)=>console.log(e))

      console.log("读取text2")

      

   
    // erc20.create('123213213213')
    // .then((result:string)=>{
    //   console.log(result)
    //    //SetBalance(Number(ethers.utils.formatEther(result)))
    // }).catch((e:Error)=>console.log(e))
  }

  const doConnect = () => {
    //client side code
    if(!window.ethereum) {
      console.log("please install MetaMask")
      return
    }
    /*
    //change from window.ethereum.enable() which is deprecated
    //call window.ethereum.request() directly
    window.ethereum.request({ method: 'eth_requestAccounts' })
    .then((accounts:any)=>{
      if(accounts.length>0) setCurrentAccount(accounts[0])
    })
    .catch('error',console.error)
    */

    //we can do it using ethers.js
    const provider = new ethers.providers.Web3Provider(window.ethereum)
    provider.send("eth_requestAccounts", [])
    .then((accounts)=>{
      //if(accounts.length>0) setCurrentAccount(accounts[0])
    }).catch((e)=>console.log(e))

  }

 



 


  return (
    <div>
    <Text><b>This is todo content</b>: {addressContract}</Text>

    <Text my={4}><b>ClassToken in current account</b>: {balance} {symbol}</Text>
</div>
  )
}
